package com.beta.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.beta.cache.CacheKeys;
import com.beta.dto.ProvinceDto;
import com.beta.entity.Provinces;
import com.beta.service.IProvincesService;
import com.beta.mapper.ProvincesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Provinces 表数据服务层接口实现类
 */
@Service
public class ProvincesService extends SuperServiceImpl<ProvincesMapper, Provinces> implements IProvincesService {

    @Autowired
    private ProvincesMapper provincesMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<ProvinceDto> getCities() {
        String cachedCities = redisTemplate.opsForValue().get(CacheKeys.CITY.getValue());
        List<ProvinceDto> cities;
        if (Objects.isNull(cachedCities)) {
            cities = provincesMapper.getCities();
            redisTemplate.opsForValue().set(CacheKeys.CITY.getValue(), JSON.toJSONString(cities), CacheKeys.CITY.getExpireSeconds().intValue(), TimeUnit.SECONDS);
        } else {
            cities = JSON.parseArray(cachedCities, ProvinceDto.class);
        }
        return cities;
    }

}